package com.ruoyi.manage.report.controller;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.celoan.entity.*;
import com.ruoyi.celoan.entity.statistics.ExTradeEffectCreditStatisticsCityEntity;
import com.ruoyi.celoan.entity.statistics.ExTradeEffectCreditStatisticsOrgEntity;
import com.ruoyi.celoan.entity.statistics.ExTradeEffectCreditStatisticsPingtaiEntity;
import com.ruoyi.celoan.handanUtils.HanDanHttpUtils;
import com.ruoyi.celoan.handanUtils.HanDanHttpUtilsNew;
import com.ruoyi.celoan.service.*;
import com.ruoyi.celoan.service.statistics.ExTradeEffectCreditStatisticsCityService;
import com.ruoyi.celoan.service.statistics.ExTradeEffectCreditStatisticsOrgService;
import com.ruoyi.celoan.service.statistics.ExTradeEffectCreditStatisticsPingtaiService;
import com.ruoyi.celoan.service.statistics.ExTradeEffectEnterprisesDetailSqsService;
import com.ruoyi.celoan.util.InterfaceMapEnum;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.FreeImagesToPdf;
import com.ruoyi.common.utils.ObjUtil;
import com.ruoyi.common.utils.StrUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.manage.enterprise.domain.EcEnterpriseFile;
import com.ruoyi.manage.enterprise.domain.EcEnterpriseInformation;
import com.ruoyi.manage.enterprise.domain.EcEnterpriseLegal;
import com.ruoyi.manage.enterprise.service.IEcEnterpriseFileService;
import com.ruoyi.manage.enterprise.service.IEcEnterpriseInformationService;
import com.ruoyi.manage.enterprise.service.IEcEnterpriseLegalService;
import com.ruoyi.manage.report.domain.ReportInterface;
import com.ruoyi.manage.report.domain.vo.ReportInterfaceVo;
import com.ruoyi.manage.report.service.IReportInterfaceService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.time.YearMonth;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 上报接口信息Controller
 *
 * @author ruoyi
 * @date 2025-08-24
 */
@Api(tags = "上报接口信息控制器")
@RestController
@RequestMapping("/manage/report")
public class ReportInterfaceController extends BaseController {
    /**
     * 配置表别名 默认空
     */
    private final static String TABLE_PREFIX = StrUtil.initTableAlias(null);
    @Autowired
    private IReportInterfaceService reportInterfaceService;

    @Autowired
    private ExTradeEffectEnterprisesDetailService exTradeEffectEnterprisesDetailService;
    @Autowired
    private ExTradeEffectPoliciesDetailService exTradeEffectPoliciesDetailService;
    @Autowired
    private ExTradeEffectFinancingrequirementsDetailService financingrequirementsDetailService;
    @Autowired
    private ExTradeEffectFinancialproductsDetailService financialproductsDetailService;
    @Autowired
    private ExTradeEffectFinancialinstitutionsDetailService financialinstitutionsDetailService;
    @Autowired
    private ExTradeEffectCreditDetailService exTradeEffectCreditDetailService;
    @Autowired
    private ExTradeEffectCreditStatisticsCityService exTradeEffectCreditStatisticsCityService;
    @Autowired
    private ExTradeEffectCreditStatisticsOrgService exTradeEffectCreditStatisticsOrgService;
    @Autowired
    private ExTradeEffectCreditStatisticsPingtaiService exTradeEffectCreditStatisticsPingtaiService;
    @Autowired
    private ExPrivatelyOperatedStatisticsService exPrivatelyOperatedStatisticsService;
    @Autowired
    private ExtradeEffectLoginLogService extradeEffectLoginLogService;
    @Autowired
    private IEcEnterpriseLegalService iEcEnterpriseLegalService;
    @Autowired
    private ExTradeEffectEnterprisesDetailSqsService effectEnterprisesDetailSqsService;

    @Autowired
    private IEcEnterpriseInformationService iEcEnterpriseInformationService;

    @Autowired
    private IEcEnterpriseFileService iEcEnterpriseFileService;

    /**
     * 查询上报接口信息列表
     */
    @ApiOperation(value = "查询上报接口信息", notes = "上报接口信息管理")
    @PreAuthorize("@ss.hasPermi('manage:report:list')")
    @GetMapping("/list")
    public TableDataInfo list(ReportInterfaceVo reportInterface, QueryWrapper<ReportInterface> queryWrapper) {
        setQueryCondition(reportInterface, queryWrapper);
        startPage();
        List<ReportInterface> list = reportInterfaceService.list(queryWrapper);
        return getDataTable(list);
    }

    private void setQueryCondition(ReportInterfaceVo reportInterface, QueryWrapper<ReportInterface> queryWrapper) {
        if (StrUtil.isNotBlank(reportInterface.getName())) {
            queryWrapper.like(TABLE_PREFIX + "name", reportInterface.getName());
        }
        queryWrapper.orderByDesc(TABLE_PREFIX + "create_time");
    }

    /**
     * 导出上报接口信息列表
     */
    @PreAuthorize("@ss.hasPermi('manage:report:export')")
    @PostMapping("/export")
    public void export(HttpServletResponse response, ReportInterfaceVo reportInterface, QueryWrapper<ReportInterface> queryWrapper) {
        if (CollUtil.isEmpty(reportInterface.getIds())) {
            setQueryCondition(reportInterface, queryWrapper);
        } else {
            queryWrapper.in(TABLE_PREFIX + "id", reportInterface.getIds());
        }
        List<ReportInterface> list = reportInterfaceService.list(queryWrapper);
        ExcelUtil<ReportInterface> util = new ExcelUtil<ReportInterface>(ReportInterface.class);
        util.exportExcel(response, list, "report");
    }

    /**
     * 获取上报接口信息详细信息
     */
    @ApiOperation(value = "获取上报接口信息", notes = "上报接口信息管理")
    @PreAuthorize("@ss.hasPermi('manage:report:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(reportInterfaceService.queryGetById(id));
    }


    @GetMapping("/generateShouquanshu")
    @Anonymous
    public AjaxResult generateShouquanshu() {
        try {

            // 获取当前年月
            YearMonth currentYearMonth = YearMonth.now();
// 当月第一天的开始时间
            LocalDateTime beginOfMonth = currentYearMonth.atDay(1).atStartOfDay();
// 下月第一天的开始时间（作为结束条件）
            LocalDateTime beginOfNextMonth = currentYearMonth.plusMonths(1).atDay(1).atStartOfDay();

// 查询当月数据
            List<EcEnterpriseInformation> list = iEcEnterpriseInformationService.lambdaQuery()
                    .ge(EcEnterpriseInformation::getCreateTime, "2025-09-01")        // createTime >= 本月第一天 00:00:00
                    .lt(EcEnterpriseInformation::getCreateTime, "2025-09-30")
                    .isNotNull(EcEnterpriseInformation::getRegisteredCapital)
                    .eq(EcEnterpriseInformation::getExamineResult, "2")// createTime < 下月第一天 00:00:00
                    .list();

            List<ExTradeEffectEnterprisesDetailSqsEntity> shangbaoFileList = new ArrayList<>();


            for (EcEnterpriseInformation enterpriseInformation : list) {
                List<EcEnterpriseFile> fileList = iEcEnterpriseFileService.lambdaQuery().eq(EcEnterpriseFile::getEnterpriseId, enterpriseInformation.getId()).eq(EcEnterpriseFile::getFileType, "6").list();
                EcEnterpriseLegal enterpriseLegal = iEcEnterpriseLegalService.lambdaQuery().eq(EcEnterpriseLegal::getEnterpriseId, enterpriseInformation.getId()).one();
                List<String> fileUrls = fileList.stream().map(m -> m.getFileUrl()).collect(Collectors.toList());
                String fileUrl = FreeImagesToPdf.generatePdfByImg(fileUrls);
                if (ObjUtil.isNull(fileUrl)) {
                    continue;
                }

                ExTradeEffectEnterprisesDetailSqsEntity enterprisesDetailSqsEntity = new ExTradeEffectEnterprisesDetailSqsEntity();
                enterprisesDetailSqsEntity.setFileUrl(fileUrl);
                enterprisesDetailSqsEntity.setEnterpriseName(enterpriseInformation.getEnterpriseName());
                enterprisesDetailSqsEntity.setUniscId(enterpriseInformation.getCreditCode());
                enterprisesDetailSqsEntity.setCount("1");
                enterprisesDetailSqsEntity.setIsflag("0");
                enterprisesDetailSqsEntity.setAuthorizedInfos("1@@2@@3@@4@@5@@6@@7@@8@@9");
                enterprisesDetailSqsEntity.setAuthorizedOrgsCode("3324523@@34563460");
                enterprisesDetailSqsEntity.setAuthSource("1");
                enterprisesDetailSqsEntity.setCount("10");
//            enterprisesDetailSqsEntity.setCaSupplier("1");
//            enterprisesDetailSqsEntity.setValidateUrl("1");
                enterprisesDetailSqsEntity.setAuthorizedStartTime("2025-06-30 10:00:00");
                enterprisesDetailSqsEntity.setAuthorizedEndTime("2025-10-30 10:00:00");
                enterprisesDetailSqsEntity.setLegalPersonName(enterpriseLegal.getName());
                enterprisesDetailSqsEntity.setLegalPersonIdCardNo(enterpriseLegal.getIdCard());
                enterprisesDetailSqsEntity.setPlatformId("1306");
                enterprisesDetailSqsEntity.setQueryUse("信息核验");
                enterprisesDetailSqsEntity.setLicenseFileType("1");
                enterprisesDetailSqsEntity.setLoanStage("3");

                effectEnterprisesDetailSqsService.save(enterprisesDetailSqsEntity);


            }

        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        return AjaxResult.success();
    }

    /**
     * 新增上报接口信息
     */
    @ApiOperation(value = "新增上报接口信息", notes = "上报接口信息管理")
    @PreAuthorize("@ss.hasPermi('manage:report:add')")
    @RepeatSubmit
    @PostMapping
    public AjaxResult add(@Validated @RequestBody ReportInterface reportInterface) {
        return toAjax(reportInterfaceService.addReportInterface(reportInterface) ? 1 : 0);
    }

    /**
     * 修改上报接口信息
     */
    @ApiOperation(value = "修改上报接口信息", notes = "上报接口信息管理")
    @PreAuthorize("@ss.hasPermi('manage:report:edit')")
    @PutMapping
    public AjaxResult edit(@RequestBody ReportInterface reportInterface) {
        return toAjax(reportInterfaceService.updateReportInterface(reportInterface) ? 1 : 0);
    }

    /**
     * 删除上报接口信息
     */
    @ApiOperation(value = "删除上报接口信息", notes = "上报接口信息管理")
    @PreAuthorize("@ss.hasPermi('manage:report:remove')")
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(reportInterfaceService.deleteReportInterfaceByIds(ids) ? 1 : 0);
    }


    @GetMapping("/ceshi")
    @Anonymous
    public AjaxResult ceshi() {
        this.exTradeEffectEnterprisesDetailService.getHanDanDataReportNew(InterfaceMapEnum.REPORT_QYTB.getDesc(), null, "130400", HanDanHttpUtilsNew.getToken());
        return AjaxResult.success("上报成功");
    }

    /**
     * 邯郸企业填报信息回传到省节点接口
     */
    @ApiOperation(value = "邯郸企业填报信息回传到省节点接口", notes = "邯郸企业填报信息回传到省节点接口")
    @RepeatSubmit
    @PreAuthorize("@ss.hasPermi('manage:report:edit')")
    @PostMapping("/enterprisesInfo")
    public AjaxResult enterprisesInfo(@RequestBody ReportInterface reportInterface) {
        if (StringUtils.isEmpty(reportInterface.getType())) {
            return AjaxResult.error("请确认接口类型是否正确且不为空");
        }

        if (reportInterface.getType().equals("QYTB")) {//企业填报信息回传到省节点接口
            this.exTradeEffectEnterprisesDetailService.getHanDanDataReport(InterfaceMapEnum.REPORT_QYTB.getDesc(), null, "130400", HanDanHttpUtils.getToken());
        } else if (reportInterface.getType().equals("RZXQ")) {
            this.financingrequirementsDetailService.getHanDanDataReport(InterfaceMapEnum.REPORT_RZXQ.getDesc(), null, "130400", HanDanHttpUtils.getToken());
        } else if (reportInterface.getType().equals("JRJGSXFK")) {
            this.exTradeEffectCreditDetailService.getHanDanDataReport(InterfaceMapEnum.REPORT_JRJGSXFK.getDesc(), null, "130400", HanDanHttpUtils.getToken());
        } else if (reportInterface.getType().equals("JRJG")) {
            this.financialinstitutionsDetailService.getHanDanDataReport(InterfaceMapEnum.REPORT_JRJG.getDesc(), null, "130400", HanDanHttpUtils.getToken());
        } else if (reportInterface.getType().equals("JRCP")) {
            this.financialproductsDetailService.getHanDanDataReport(InterfaceMapEnum.REPORT_JRCP.getDesc(), null, "130400", HanDanHttpUtils.getToken());
        } else if (reportInterface.getType().equals("ZCXX")) {
            this.exTradeEffectPoliciesDetailService.getHanDanDataReport(InterfaceMapEnum.REPORT_ZCXX.getDesc(), null, "130400", HanDanHttpUtils.getToken());
        } else if (reportInterface.getType().equals("TJ_CITY")) {
            this.exTradeEffectCreditStatisticsCityService.getHanDanDataReport(InterfaceMapEnum.REPORT_TJ_CITY.getDesc(), null, "130400", HanDanHttpUtils.getToken());
        } else if (reportInterface.getType().equals("TJ_PINGTAI")) {
            this.exTradeEffectCreditStatisticsPingtaiService.getHanDanDataReport(InterfaceMapEnum.REPORT_TJ_PINGTAI.getDesc(), null, "130400", HanDanHttpUtils.getToken());
        } else if (reportInterface.getType().equals("TJ_ORG")) {
            this.exTradeEffectCreditStatisticsOrgService.getHanDanDataReport(InterfaceMapEnum.REPORT_TJ_ORG.getDesc(), null, "130400", HanDanHttpUtils.getToken());
        } else if (reportInterface.getType().equals("TJ_MYQY")) {
            this.exPrivatelyOperatedStatisticsService.getHanDanDataReport(InterfaceMapEnum.REPORT_TJ_ORG.getDesc(), null, "130400", "ces");
        } else if (reportInterface.getType().equals("SBLOGS")) {
            this.extradeEffectLoginLogService.getHanDanDataReport(InterfaceMapEnum.SBLOGS.getDesc(), null, "130400", HanDanHttpUtils.getToken());
        }
        return AjaxResult.success("上报数据成功");
    }

    @GetMapping("/reportRecord")
    public TableDataInfo getAllReportRecords(String type) {


        if (type.equals("QYTB")) {//企业填报信息回传到省节点接口
            startPage();
            List<ExTradeEffectEnterprisesDetailEntity> list = this.exTradeEffectEnterprisesDetailService.list(new LambdaQueryWrapper<ExTradeEffectEnterprisesDetailEntity>().orderByDesc(ExTradeEffectEnterprisesDetailEntity::getSettlingTime));
            return getDataTable(list);
        } else if (type.equals("RZXQ")) {
            startPage();
            List<ExTradeEffectFinancingrequirementsDetailEntity> list = this.financingrequirementsDetailService.list();
            return getDataTable(list);
        } else if (type.equals("JRJGSXFK")) {
            startPage();
            List<ExTradeEffectCreditDetailEntity> list = this.exTradeEffectCreditDetailService.list();
            return getDataTable(list);
        } else if (type.equals("JRJG")) {
            startPage();
            List<ExTradeEffectFinancialinstitutionsDetailEntity> list = this.financialinstitutionsDetailService.list();
            return getDataTable(list);
        } else if (type.equals("JRCP")) {
            startPage();
            List<ExTradeEffectFinancialproductsDetailEntity> list = this.financialproductsDetailService.list();
            return getDataTable(list);
        } else if (type.equals("ZCXX")) {
            startPage();
            List<ExTradeEffectPoliciesDetailEntity> list = this.exTradeEffectPoliciesDetailService.list();
            return getDataTable(list);
        } else if (type.equals("TJ_CITY")) {
            startPage();
            List<ExTradeEffectCreditStatisticsCityEntity> list = this.exTradeEffectCreditStatisticsCityService.list();
            return getDataTable(list);
        } else if (type.equals("TJ_PINGTAI")) {
            startPage();
            List<ExTradeEffectCreditStatisticsPingtaiEntity> list = this.exTradeEffectCreditStatisticsPingtaiService.list();
            return getDataTable(list);
        } else if (type.equals("TJ_ORG")) {
            startPage();
            List<ExTradeEffectCreditStatisticsOrgEntity> list = this.exTradeEffectCreditStatisticsOrgService.list();
            return getDataTable(list);
        } else if (type.equals("TJ_MYQY")) {
            startPage();
            List<ExPrivatelyOperatedStatisticsEntity> list = this.exPrivatelyOperatedStatisticsService.list();
            return getDataTable(list);
        } else if (type.equals("SBLOGS")) {
            startPage();
            List<ExtradeEffectLoginLogEntity> list = this.extradeEffectLoginLogService.list();
            return getDataTable(list);
        }

        return null;
    }

    @GetMapping("/getStatisall")
    @Anonymous
    public AjaxResult getStatisall() {
        ExPrivatelyOperatedStatisticsEntity entity = exPrivatelyOperatedStatisticsService.lambdaQuery()
                .orderByDesc(ExPrivatelyOperatedStatisticsEntity::getExternalSystemId)
                .last("LIMIT 1")
                .one();

        return AjaxResult.success(entity);
    }


    @Autowired
    ExTradeEffectSelectService exTradeEffectSelectService;


    @PostMapping("/uploadAuthorization")
    @Anonymous
    public AjaxResult uploadAuthorization() {
        List<ExTradeEffectEnterprisesDetailSqsEntity> list = effectEnterprisesDetailSqsService.lambdaQuery().eq(ExTradeEffectEnterprisesDetailSqsEntity::getIsflag, "1").list();
        if (list.size() > 0) {
            ExTradeEffectEnterprisesDetailSqsEntity exTradeEffectEnterprisesDetailSqsEntity = list.get(0);
            return exTradeEffectSelectService.shouQuan(exTradeEffectEnterprisesDetailSqsEntity);
        }

        return AjaxResult.error();
    }

}
